package com.aggron.util;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;

/**
 * @author  liuhuan on 2018/6/2.
 */
@Slf4j
public class JsonMapper {
    private static  ObjectMapper objectMapper=new ObjectMapper();

    static {
        //config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

    }

    public static <T> String obj2String(T src){
        if(src==null){
            return null;
        }
        try {
            return src instanceof String ?(String)src:objectMapper.writeValueAsString(src);
        }catch (Exception e){
            log.warn("parse object to string error,{}",e);
            return null;
        }
    }

    public static <T> T string2Obj(String src, TypeReference<T> typeReference){
        if(src==null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)?src:
                    objectMapper.readValue(src,typeReference.getClass()));
        }catch (Exception e){
            log.warn("parse  string to object  error,string :{},TypeReference:{ },e:{}",src,typeReference.getType(),e);
            return null;
        }
    }
}
